package com.atguigu.b_poly;
/*
    多态的弊端 : 父引用不能访问子类的特有成员 [只能访问父类有的成员]
 */
public class Demo {
    public static void main(String[] args) {
        //以多态的方式创建对象 : 父引用指向子类对象
        Animal a1 = new Dog();
        a1.eat();
        //解决问题 : 向下转型
        Dog dog = (Dog) a1;
        dog.lookHome();
        System.out.println("-----------------");
        Animal a2 = new Cat();
        a2.eat();
        Cat cat = (Cat) a2;
        cat.catchMouse();
        System.out.println("-----------------");
        Animal a3 = new Pig();
        a3.eat();
        Pig pig = (Pig) a3;
        pig.sleep();
        //上方代码脑残 !!
        System.out.println("------------------------");
        //创建对象就创建子类对象
        Dog d = new Dog();
        use(d);

        Cat c = new Cat();
        use(c);

        Pig p = new Pig();
        use(p);

        Animal animal = new Animal();
        use(animal);
    }

    public static void use(Animal animal){ // = d = new Dog()
        animal.eat();

        //做向下转型
        if (animal instanceof Dog){
            Dog dog = (Dog) animal;
            dog.lookHome();
            return;
        }

        if (animal instanceof Cat){
            Cat cat = (Cat) animal;
            cat.catchMouse();
            return;
        }

        if (animal instanceof Pig){
            Pig pig = (Pig) animal;
            pig.sleep();
            return;
        }


    }

    //把方法的返回值类型写成父类型
    public static Animal getAnimal(){
//        Dog dog = new Dog();
//        return dog;

//        Cat cat = new Cat();
//        return cat;

//        Pig p = new Pig();
//        return p;

        Animal animal = new Animal();
        return animal;
    }
}
//猫狗案例
class Animal{
    public void eat(){
        System.out.println("动物吃东西 ! ");
    }
}

class Dog extends Animal {
    @Override
    public void eat() {
        System.out.println("狗吃骨头 ! ");
    }

    //特有行为
    public void lookHome(){
        System.out.println("狗看家 ! ");
    }
}

class Cat extends Animal {
    @Override
    public void eat() {
        System.out.println("猫吃罐头 ! ");
    }

    //特有行为
    public void catchMouse(){
        System.out.println("猫抓老鼠 ! ");
    }
}

class Pig extends Animal {
    @Override
    public void eat() {
        System.out.println("猪吃饲料 ! ");
    }

    //特有行为
    public void sleep(){
        System.out.println("猪天天睡觉 ! ");
    }
}